import clone from 'clone'
import ArrayUtil from '@zh/common-utils/utils/array'

import { WuJie as MicroAppLayout } from './layouts'
import MicroApp from './micro-app'

const routeConfig = { pc: [], mobile: [] },
  microapps = []

const install = (Vue, router) => {
  if (install.used) {
    return
  }

  Object.assign(router, {
    afterDynamicRoutesBuild () {
      return new Promise((resolve) => {
        resolve()
      })
    },
    /**
     * 加载动态路由配置文件
     * @param {*} fileList
     * @param {*} key
     */
    loadRouteConfigFiles (fileList, key = 'pc') {
      let configList = []
      fileList.keys().map(filename => {
        const configs = fileList(filename)
        Object.keys(configs).map(k => {
          configList = configList.concat(configs[k])
        })
      })
      routeConfig[key] = (routeConfig[key] || []).concat(configList)
    },
    /**
     * 扁平化路由
     * @param {*} key
     * @returns
     */
    flatRoutes (configures) {
      const routeMap = {}
      ArrayUtil.flat(configures, 'children').map(route => {
        route.meta = route.meta || {}
        route.title = route.meta.title
        route.meta._parent = route._parent
        if (!route.path) {
          return
        }
        // path为绝对路径，则提升该节点到父节点同一级（从父节点的 children 中移除该节点）
        if (route.path.startsWith('/')) {
          // 从父节点中移除该节点
          route._parent?.children?.splice(route._parent?.children.indexOf(route), 1)
          // 标记为绝对路径
          route.meta.absolute = true
        }
        if (route.path.startsWith('http://') || route.path.startsWith('https://')) {
          route.meta.absolute = true
        } else if (!route.path.startsWith('/')) {
          // 补全相对路径
          const pathList = ArrayUtil.getParents(route).filter(p => p.path && !p.path.startsWith('https://') && !p.path.startsWith('http://')).map(p => p.path)
          route.path = `/${pathList.join('/')}/${route.path}`.replace(/\/\/+/g, '/')
        }
        routeMap[route.path] = route
      })
      return routeMap
    },

    getRouteConfig (key = 'pc') {
      return routeConfig[key]
    },

    buildMicroApp (options, meta = {}) {
      if (options.root && options.root !== '/' && options.root !== '') {
        options.code = options.root.substring(1).replaceAll('/', '-') + '-' + options.code
      }
      if (this.hasMicroApp(options.code)) {
        return
      }
      // 注册微应用
      const config = MicroApp.setupApp(options.code, options.host, options)
      // 构建微应用路由
      const route = {
        path: `/${options.code}/:path*`,
        meta: {
          ...meta, subapp: config
        },
        component: {
          render (e) {
            return e(MicroAppLayout)
          }
        }
      }
      microapps.push(options.code)
      return route
    },
    hasMicroApp (appCode) {
      return microapps.includes(appCode)
    }
  })

  install.used = true
}

export default install